<template>
    <div class="app-container">
        <el-row :gutter="20">
            <el-col :span="8">
                <el-col :span="1">
                    <i :class="[treeShow ? 'el-icon-s-fold treeI' : 'el-icon-s-unfold treeI']" @click="toggerTree" />
                </el-col>
            </el-col>
            <el-col style="text-align:right;margin-top: -3px;">
                <el-button size="small" class="filter-item" style="margin-left:10px;" type="primary"  @click="CopyFormula">
                复制工资项
              </el-button>  
                <el-button size="small" class="filter-item" style="margin-left: 10px;" type="primary"
                    @click="handleQuery">重置</el-button>
                <el-button size="small" class="filter-item" style="margin-left: 10px;" type="primary"
                    v-loading="saveDataLoading" @click="saveData">
                    保存</el-button>
            </el-col>

        </el-row>
        <div ref="box" class="box">
            <div class="left" :class="[isActive ? 'wid' : 'wids']">
                <div :class="[treeShow ? 'treeShow' : 'treeNotShow']" :style="{ 'height': treeHeight + 'px' }">
                    <AgencyTree class="agencyTree" @handleTreeQuery="handleTreeQuery"
                        @getFirstAuthAgencyData="getFirstAuthAgencyData" />
                </div>
            </div>

            <div v-show="Show" class="resize" title="收缩侧边栏" />
            <div class="mid" :class="[isActive ? 'mids' : 'min']">
                <el-row>
                    <el-col>
                        <el-row style="display: flex;justify-content: center;">
                            <el-col :span="6">
                                <span>{{ this.agencyName }}</span>
                                <el-card shadow="always">
                                    <div slot="header" class="clearfix">
                                        <span>人员类型列表: </span>
                                    </div>
                                    <el-table ref="agencyTable" v-loading="agencyLoading" :data="personTypeData"
                                        :height="tableHeight" :stripe="true"
                                        :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
                                        style="width: 100%" :header-cell-class-name="cellCheckbox"
                                        @selection-change="handleAgencySelectionChange"
                                        @row-click="handleAgencyRowClick" @select="tableSelect">
                                        <template slot="empty">
                                            <tableEmpty />
                                        </template>
                                        <el-table-column type="selection" width="50" />
                                        <el-table-column type="index" label="序号" width="50" />
                                        <el-table-column prop="personTypeName" label="名称" />
                                    </el-table>
                                </el-card>
                            </el-col>
                            <el-col :span="6">
                                <div style="margin-top: 50%; margin-left: 50%;" />
                            </el-col>
                            <el-col :span="6">
                                <el-card shadow="always">
                                    <div slot="header" class="clearfix">
                                        <span>工资项列表: </span>
                                    </div>
                                    <el-table ref="salaryTable" v-loading="salaryLoading" :data="salaryData"
                                        :height="tableHeight" :stripe="true" style="width: 100%"
                                        :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
                                        @selection-change="handleSalarySelectionChange"
                                        @row-click="handleSalaryRowClick">
                                        <template slot="empty">
                                            <tableEmpty />
                                        </template>
                                        <el-table-column type="selection" width="50" :selectable="selectable" />
                                        <el-table-column type="index" label="序号" width="50" />
                                        <el-table-column prop="salaryName" label="工资项名称" />
                                    </el-table>
                                </el-card>
                            </el-col>
                        </el-row>
                    </el-col>
                </el-row>
            </div>
            <Drag ref="icon" />
        </div>
        <el-dialog  v-dialogDrag  
       :close-on-click-modal="false"
        :width=" '52%'"
        title="复制工资项"
        center
        :visible.sync="dialogFormCopyFormula"
    >
     <el-form
        ref="dataForm"
        class="dialog-Backgroundcolor"
       
        label-position="right"
        label-width="0px"
      >
         <div style="height:500px;overflow:auto;">
            <el-tree
              id="onlyLeafShow"
              ref="tree"
              node-key="id"
              show-checkbox
              :highlight-current="true"
              :data="agencyTreeData"
              :props="defaultProps"
              :default-expanded-keys="['0']"
              :filter-node-method="filterNode"
               @handleTreeQuery="handleTreeQuery"
              @getFirstAuthAgencyData="getFirstAuthAgencyData" 
            />
          </div>
         
          <el-button
            type="primary"
            style="float:right;"
             :loading="verifyLoading"
            @click="batchHandleAudit"
          >
            复制工资项
          </el-button>
      </el-form>
    </el-dialog>  
    </div>



    
</template>

<script>

import tableEmpty from '@/components/table/empty'
import { querySalaryBasedataInfo, queryPersonType, selSalaryBasedata, inseStsalaryBasedata,CopySalaryItem } from '@/api/salaryConfigManage/salaryProjectConnect'
import AgencyTree from '@/components/tree/agencyTree'
import { getAuthAgencyTree, getFirstAuthAgencyData } from '@/api/baseInfo'

import Drag from '@/components/Drag'

import { all } from 'q'
export default {
    name: 'SalaryProjectConnect',
    components: { tableEmpty, Drag, AgencyTree },
    data() {
        return {
            tableHeight: null,
            agencyLoading: false,
            personTypeData: [],
            salaryData: [],
            agencyTreeData: [],
            salaryLoading: true,
            saveDataLoading: false,
            dialogFormCopyFormula:false,
            agencySelectData: [], // 单位表格选中数据
            salarySelectData: [], // 工资表格选中数据
            personTypeCode: '', // 左边选中的
            verifyLoading: false,
            defaultProps: {
                children: 'children',
                label: 'label'
            },
            treeData: '',
            treeShow: false,
            isActive: true,
            treeHeight: null,
            Show: false,
            agencyId: '',
            agencyName: '',
            // 中共内蒙古自治区委员会办公厅
            // 2EC30725A77B42CDBBBAFE6332BA8480
            form: {
            id: '',
            calcOrder: '',
            salaryId: '',
            formula: '',
            inputFormula: '',
            meritPayCodeList: ''
      },
        }
    
    },
  
    watch: {
        salaryData(val) {
            this.doLayout()
        },
        personTypeData(val) {
            this.doLayout()
        },

    },
    created() {
        this.treeData = this.$store.getters.getFirstAuthAgencyData
        this.querySalaryBasedataInfo()
        this.getqueryPersonType()
    },
    mounted() {
        this.getTbHeight()
        this.getTeHeight()
    },
    beforeMount() {
        window.addEventListener('resize', this.getTbHeight)
    },
    methods: {
        CopyFormula(){
            this.getTreeData()
            this.dialogFormCopyFormula = true
        },
        batchHandleAudit(){
     
            const allAgencyId = this.$refs.tree.getCheckedKeys(true)
            if (allAgencyId.length === 0) {
            this.$message({
                message: '请选择至少选择一个单位',
                type: 'warning',
                showClose: true,
                duration: 4000
            })
            return
            }
            this.verifyLoading = true
            this.form.agencyId = this.agencyId
            const params = {}
            params['agencyIds'] = allAgencyId
            params['agencyId'] = this.agencyId
            CopySalaryItem(params)
            .then(() => {
                this.$message({
                    message: '保存成功',
                    type: 'success',
                    showClose: true,
                    duration: 4000
                })
                this.verifyLoading = false
                this.dialogFormCopyFormula = false 
                }).catch(() => {
                this.verifyLoading = false
                })
      
        },
        getTreeData() {
            getAuthAgencyTree().then(response => {
                this.agencyTreeData = response.data
            })
        },
        filterNode(value, data) {
            if (!value) return true
            return data.label.indexOf(value) !== -1
        },
        toggerTree() {

            this.treeShow = !this.treeShow
            this.isActive = !this.isActive//侧边栏
            this.Show = !this.Show
        },
        getTeHeight() {
            this.treeHeight = window.innerHeight - 200
        },
        getFirstAuthAgencyData(data) {
            this.treeData = data
            this.agencyId = data.id;
            this.agencyName=data.code
        },
        handleTreeQuery(data) {
            if (data && data.isleaf === '1') {
                this.treeData = data
            }
        },
        //获取点击的树信息
        handleTreeQuery(data) {

            if (data && data.isleaf === '1') {

                this.agencyId = data.id
                this.agencyName = data.label.split('-', 2)[1]
                this.treeData = data
                this.handleQuery() //树信息重置

            }
          
        },
        // 保存
        saveData() {
            this.saveDataLoading = true
            if (this.agencySelectData.length === 0) {
                this.$message({
                    showClose: true,
                    message: '请选择人员类型',
                    type: 'warning',
                    duration: 4000
                })
                this.saveDataLoading = false
                return

            }

            if (this.salarySelectData.length === 0) {
                this.$message({
                    showClose: true,
                    message: '请选择工资项',
                    type: 'warning',
                    duration: 4000
                })
                this.saveDataLoading = false
                return
            }

            const tmplist = []

            for (const item of this.salarySelectData) {
                const object = {
                    agencyId: this.agencyId,//单位id
                    salaryId: item.id,//工资id
                    isAccsalwithhold: item.computeFormula,
                    columnName: item.salaryCode,//工资
                    personType: this.agencySelectData[0].personTypeName,//人员名称
                    personTypeCode: this.agencySelectData[0].personTypeCode,//人员id
                    salaryName: item.salaryName,//工资名称
                    agencyName: this.agencyName//单位名称
                }
                tmplist.push(object)
                this.saveDataLoading = false
            }

            //         var data = {}
            //   data['agency'] = this.agencySelectData
            //   data['salary'] = this.salarySelectData
            //   data['flag'] = 'salary'
            inseStsalaryBasedata(tmplist).then(response => {
                this.$message({
                    showClose: true,
                    message: '保存成功',
                    type: 'success',
                    duration: 4000
                })
                this.saveDataLoading = false
            })
        },
        //重置
        handleQuery() {
            this.$refs.salaryTable.clearSelection()
            this.$refs.agencyTable.clearSelection()
            this.querySalaryBasedataInfo()
            this.saveDataLoading = false
        },
        // 获取左边列表的信息
        getqueryPersonType() {
            this.agencyLoading = true
            queryPersonType().then(respnse => {

                this.personTypeData = respnse.data
                this.agencyLoading = false
            })

        },
        // 获取右边列表的信息
        querySalaryBasedataInfo() {
            querySalaryBasedataInfo().then(response => {
                this.salaryData = response.data
                this.salaryLoading = false
                this.$nextTick(()=>{
                   this.salaryXz()
                })
            })
        },
        //默认勾选s1 or s2
         salaryXz(){
            this.salaryData.forEach(val => {
                   
                   if(val.salaryCode === 's2' || val.salaryCode === 's1'){
                       this.$refs.salaryTable.toggleRowSelection(val, true)
                   }
               })     
        },
        //获取树id
        getagencyId() {
            querySalaryBasedataInfo().then(response => {
                this.agencyData = response.data
                this.salaryLoading = false

            })

        },
        // 点击工资项表格行选中复选框
        handleSalaryRowClick(row) {
            if (row.salaryCode !== 's1' && row.salaryCode !== 's2') {
                this.$refs.salaryTable.toggleRowSelection(row)
            }
        },
        // 点击人员类型列表选择对应工资项
        handleSalarySelectionChange(val) {
            this.salarySelectData = val
            this.$nextTick(()=>{
                   this.salaryXz()
                })
        },
        tableSelect(row) {
            if (this.agencySelectData.length > 0) {
                for (let i = 0; i < row.length; i++) {
                    if (row[i].personTypeId !== this.agencySelectData[0].personTypeId) {
                        // 获取表格选中数据。 如果和当前不一致，取消选中
                        const selectionData = this.$refs.agencyTable.selection
                        for (let j = 0; j < selectionData.length; j++) {
                            if (selectionData[j].personTypeId !== row[i].personTypeId) {
                                this.$refs.agencyTable.toggleRowSelection(
                                    selectionData[j],
                                    false
                                )
                            }
                        }
                    }
                }
            }
            return
        },
        // 点击单位表格行选中复选框
        handleAgencyRowClick(row) {
             
            // 如果当前时选中状态，在点击该数据时，取消选中
            if (this.agencySelectData.length > 0) {
                if (row.personTypeId !== this.agencySelectData[0].personTypeId) {
                  
                    this.$refs.agencyTable.clearSelection()
                    this.$refs.agencyTable.toggleRowSelection(row)
                } else {
                    this.$refs.agencyTable.toggleRowSelection(row)
                }
            } else {
                this.$refs.agencyTable.toggleRowSelection(row)
            }
            
        },
        // 单位表格选中数据
        handleAgencySelectionChange(val) {
            this.$refs.salaryTable.clearSelection()
            const array = []
            // 获取表格选中数据,放到数组中缓存
            const selectionData = this.$refs.agencyTable.selection
            for (let i = 0; i < val.length; i++) {
                if (selectionData[0].personTypeId === val[i].personTypeId) {
                    array.push(val[i])
                }
            }
            this.agencySelectData = selectionData
            // 获取单位现有的工资项
            if (val.length > 0) {
                this.personTypeCode = selectionData[0].personTypeCode
                this.queryAgencySalaryInfoByAgencyId()
            } else {
                // 当单位表格取消选中时，将工资项表格选中状态清空
                this.$refs.salaryTable.clearSelection()
            }
        },
        // 根据单位id查询已挂接的工资项
        queryAgencySalaryInfoByAgencyId() {
            const tmp = {
                personTypeCode: this.personTypeCode,
                agencyId: this.agencyId
            }
            console.log(this.agencyId);
            selSalaryBasedata(tmp).then(respose => {

                // 如果有挂接，将已挂接的工资项选中
                if (respose.data.length > 0) {
                    respose.data.forEach(val => {
                        this.salaryData.forEach(row => {
                            if (val.salaryId === row.id || row.salaryCode === 's1' || row.salaryCode === 's2') {
                                this.$refs.agencyTable.toggleRowSelection(row, false)
                                this.$refs.salaryTable.toggleRowSelection(row, true)
                                return
                            }
                        })
                    })
                }
            })
        },
        cellCheckbox(row) {
            if (row.columnIndex === 0) {


                return 'disabledCheck'
            }
        },
        // 获取table高度的方法
        getTbHeight() {
            this.tableHeight = window.innerHeight - 350
        },
        selectable(row) {
            // 实发项和应发项复选框disable，不允许修改
            if (row.salaryCode === 's1' || row.salaryCode === 's2') { return false } else { return true }
        },
        /* 重新渲染table组件 */
        doLayout() {
            this.$nextTick(() => {
                this.$refs.salaryTable.doLayout()
                this.$refs.agencyTable.doLayout()
            })
        }

    }

}
</script>

<style lang="scss" scoped>
@import "~@/styles/border.scss";

/*引入公共样式*/
.el-table {
    margin-top: 5px;

    ::v-deep .disabledCheck {
        .cell {
            .el-checkbox {
                .el-checkbox__input {
                    display: none !important;
                }
            }
        }
    }
}

.el-card {
    border: 10px solid #65afff;
    box-shadow: 10px 10px 5px #888;
}

.app-title {
    margin-bottom: 15px;
    height: 20px;
    border-bottom: 1px solid #dcdfe6;
}
</style>
